package ivansalvadori.diariopushweb.service.impl;

import ivansalvadori.diariopushweb.dao.DiarioDAO;
import ivansalvadori.diariopushweb.dao.TermoDAO;
import ivansalvadori.diariopushweb.dao.UsuarioDAO;
import ivansalvadori.diariopushweb.model.Diario;
import ivansalvadori.diariopushweb.model.Termo;
import ivansalvadori.diariopushweb.model.Usuario;
import ivansalvadori.diariopushweb.service.UsuarioService;

import java.util.List;

import javax.xml.bind.ValidationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UsuarioServiceImpl implements UsuarioService {

	@Autowired
	private UsuarioDAO usuarioDAO;

	@Autowired
	private TermoDAO termoDAO;

	@Autowired
	private DiarioDAO diarioDAO;

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public int inserir(Usuario usuario) throws ValidationException {
		int result = 0;

		if (isEmailDisponivel(usuario.getEmail())) {
			usuario.setSituacao("ativo");
			result = usuarioDAO.inserir(usuario);
		}

		else {
			throw new ValidationException("Email já cadastrado no sistema.");
		}

		return result;

	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public void inserirTermo(Termo termo) {
		termoDAO.inserir(termo);
	}

	@Override
	public Usuario login(String email, String senha) throws ValidationException {
		Usuario usuario = usuarioDAO.getByEmail(email);
		if (usuario != null) {

			if (usuario.getSenha().equals(senha)) {
				return usuario;
			} else {
				throw new ValidationException("Senha inválida");
			}
		} else {
			throw new ValidationException("Email não encontrado");
		}
	}

	@Override
	public List<Termo> listarTermos(Usuario usuario) {
		return termoDAO.listar(usuario);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public void removerTermo(int codigo) {
		termoDAO.remover(codigo);
	}

	@Override
	public List<Diario> listarDiarios() {
		return diarioDAO.listar();
	}

	@Override
	public boolean isEmailDisponivel(String email) {
		if (usuarioDAO.getByEmail(email) == null) {
			return true;
		}

		return false;

	}
}
